package com.navi.core.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.navi.core.service.IErrorListenerService;
import com.navi.core.tx.errorInfo.ErrorInfoI;
import com.navi.core.tx.errorInfo.ErrorInfoO;
import com.navi.core.util.JacksonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import static com.navi.core.constant.GenericDef.*;

@Service
public class ErrorListenerServiceImpl implements IErrorListenerService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public ErrorInfoO saveErrorMsg(ErrorInfoI inTrx) {
        ErrorInfoO outTrx = new ErrorInfoO();

        logger.error("{}: Error msg:{}, \nURL: {}, \nLine: {}, \nCol: {}, \nError: {}.",
                JAVASCRIPT_ERROR_LOG, inTrx.getMsg(), inTrx.getUrl(), inTrx.getLine(), inTrx.getCol(), inTrx.getError());

        outTrx.setRtn_code(RETURN_CODE_OK);
        outTrx.setRtn_mesg(RETURN_MESG_OK);
        return outTrx;
    }

    @Override
    public String subMainProc(String strInObj) {
        ErrorInfoO outTrx = new ErrorInfoO();

        ErrorInfoI inTrx = JacksonUtil.fromJson(strInObj, ErrorInfoI.class);
        logger.info(strInObj);

        String actionFlg = inTrx != null ? inTrx.getAction_flg() : "";
        switch (actionFlg) {
            case "S":
                outTrx = this.saveErrorMsg(inTrx);
                break;
            default:
                break;
        }
        final String strOutTrx = JSON.toJSONString(outTrx, SerializerFeature.DisableCircularReferenceDetect);
        logger.info(strOutTrx);

        return strOutTrx;
    }
}
